package com.paper.tiger.easy.rpc.s.client;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

/**
 * spring Context 上下文
 *
 * @author 鸠摩智
 */
@Component
public class SpringContextSupport implements ApplicationContextAware {

    private static ConfigurableApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 注入上下文对象
        context = (ConfigurableApplicationContext) applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        T result = null;
        if(context != null) {
            result = context.getBean(clazz);
        }
        return result;
    }

    public static String getProperty(String key) {
        String result = null;
        if(context != null) {
            result = context.getEnvironment().getProperty(key);
        }
        return result;
    }
    
    public static Object getBean(String beanId) {
        Object result = null;
        if(context != null) {
            result = context.getBean(beanId);
        }
        return result;
    }

    public static <T> T getBean(String beanName, Class<T> requiredType) {
        T result = null;
        if(context != null) {
            result = context.getBean(beanName, requiredType);
        }
        return result;
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationTag) throws BeansException{
        Map<String, Object> result = new HashMap<String, Object>();
        if(context != null) {
            result = context.getBeansWithAnnotation(annotationTag);
        }
        return result;
    }

    public static ConfigurableListableBeanFactory getBeanFactory() {
        return  context.getBeanFactory();
    }

}
